/******************************************************************************
 * @File name   :      MemberPackageServiceImpl.java
 *
 * @Author      :      JIZHANGS
 *
 * @Date        :      Jul 28, 2015
 *
 * @Copyright Notice: 
 * Copyright (c) 2015 Capgemini, Inc. All  Rights Reserved.
 * This software is published under the terms of the Capgemini Software
 * License version 1.0, a copy of which has been included with this
 * distribution in the LICENSE.txt file.
 * 
 * 
 * ----------------------------------------------------------------------------
 * Date                   Who         Version        Comments
 * Jul 28, 2015 9:33:15 AM        JIZHANGS     1.0            Initial Version
 *****************************************************************************/
package com.cap.bts.crmdp.dealer.mars.service.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.cap.bts.commonfunc.common.constant.SmsTemplateNoConstants;
import com.cap.bts.commonfunc.common.constant.SmsTemplateVariable;
import com.cap.bts.commonfunc.common.dto.SmsContentDetailDto;
import com.cap.bts.crmdp.dealer.mars.constants.MARSConstants;
import com.cap.bts.crmdp.dealer.mars.service.IMarsMemberPackageService;
import com.cap.bts.crmdp.dealer.member.dao.IMaintainCarPlateDao;
import com.cap.bts.crmdp.dealer.member.dao.IMaintainMemberDao;
import com.cap.bts.crmdp.dealer.member.domain.CarPlateInfo;
import com.cap.bts.crmdp.dealer.member.domain.MemberInfo;
import com.cap.bts.crmdp.dealer.purchase.constants.PurchaseConstants;
import com.cap.bts.crmdp.dealer.purchase.dao.ICardInventoryDao;
import com.cap.bts.crmdp.dealer.purchase.dao.IMemberPackageDao;
import com.cap.bts.crmdp.dealer.purchase.dao.IPackageDefinitionDao;
import com.cap.bts.crmdp.dealer.purchase.domain.CardInventory;
import com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo;
import com.cap.bts.crmdp.dealer.purchase.domain.PackageDefinition;
import com.cap.bts.crmdp.dealer.purchase.dto.MemberPackageInfoSubmitDto;
import com.cap.bts.crmdp.dealer.redemption.dao.IPackageRedemptionDao;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberAndDealerInfoDto;
import com.cap.bts.crmdp.dealer.redemption.dto.MemberPackagesReportDto;
import com.cap.bts.crmdp.dealer.redemption.dto.ShowMemberPackageInfoReportDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmCancelOrderResultDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmOrderDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmSettlementDto;
import com.cap.bts.crmdp.webservice.dto.WSCrmSettlementResultDto;
import com.cap.bts.framework.codemapping.domain.CodeInfo;
import com.cap.bts.framework.codemapping.service.ICodeMapping;
import com.cap.bts.framework.common.constant.CodeMappingType;
import com.cap.bts.framework.common.constant.CommonConstants;
import com.cap.bts.framework.common.exception.AppException;
import com.cap.bts.framework.common.service.impl.BaseServiceImpl;
import com.cap.bts.framework.common.util.Utils;
import com.cap.bts.framework.sms.service.ISmContentService;
import com.cap.bts.framework.usermgnt.dao.IUserDao;
import com.cap.bts.framework.usermgnt.domain.User;

/**
 *
 */
@Transactional(rollbackFor = AppException.class)
@Service
public class MarsMemberPackageServiceImpl extends BaseServiceImpl implements IMarsMemberPackageService {

    private static final Logger LOGGER = Logger.getLogger(MarsMemberPackageServiceImpl.class);

    @Resource(name = "memberPackageDao")
    private IMemberPackageDao memberPackageDao;

    @Autowired
    private IMaintainMemberDao memberDao;

    @Autowired
    private IMaintainCarPlateDao carPlateDao;
    
    
    @Autowired
    private IPackageDefinitionDao packageDefinitionDao;
    
    @Autowired
    private ICardInventoryDao cardInventoryDao;

    
    @Autowired
    private ISmContentService smContentService;

    @Autowired
    private ICodeMapping codeMappingService;

    @Autowired
    private IUserDao userDao;
    @Autowired
    private IPackageRedemptionDao packageRedemptionDao;

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Jul 28, 2015
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#checkMemberPackageExsit(com.cap.bts.crmdp.dealer.purchase.dto.MemberPackageInfoSubmitDto)
     **/
    @Override
    public Boolean checkMemberPackageExsit(MemberPackageInfoSubmitDto dto) throws AppException {
        MemberPackageInfo mpi = new MemberPackageInfo();
        PackageDefinition pd = new PackageDefinition();
        pd.setId(dto.getPackageDefId());
        mpi.setPackageDefinition(pd);
        mpi.setPackageNumber(dto.getPackageNumber());
        mpi = memberPackageDao.getUnPurchaseMemberPackageInfo(mpi);
        if (mpi == null) {
            return false;
        }
        return true;
    }
    
    /**
     * 
     * {@inheritDoc} 
     * overridden:
     * @Date        :      Nov 16, 2015
     * @see com.cap.bts.crmdp.dealer.mars.service.IMarsMemberPackageService#getMemberPackageInfoByPackageNumber(java.lang.String)
    *
     */
    @Override
    public MemberPackageInfo getMemberPackageInfoByPackageNumber(String packageNumber) throws AppException {
        MemberPackageInfo mpi = new MemberPackageInfo();
        mpi.setPackageNumber(packageNumber);
        return memberPackageDao.getPurchasedMemberPackageInfo(mpi);
    }
    @Override
    public MemberPackageInfo getPackageInfoByPackageNumber(String packageNumber) throws AppException {
    	return memberPackageDao.getMemeberPackageInfoByPackageNumber(packageNumber);
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Aug 4, 2015
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#updateMemberPackageInfo(com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo)
     **/
    @Override
    public void updateMemberPackageInfo(MemberPackageInfo mpi) throws AppException {
        memberPackageDao.updateMemberPackageInfo(mpi);
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Aug 4, 2015
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#updateMemberPackageInfo(com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo)
     **/
    @Override
    public void updateMemberPackageInfoById(MemberPackageInfo mpi) throws AppException {
        memberPackageDao.updateMemberPackageInfoById(mpi);
    }

    @Override
    public void processExpiredMemberPackage() throws AppException {
        try {
            List<MemberPackageInfo> memberPackageInfoList = memberPackageDao
                .getAllActiveMemberPackageList();
            for (MemberPackageInfo memberPackageInfo : memberPackageInfoList) {
                if (memberPackageInfo != null
                    && (int) memberPackageInfo.getStatus() == PurchaseConstants.PACKAGE_STATUS_ACTIVED) {
                    Calendar currentCalendar = Calendar.getInstance();
                    currentCalendar.setTime(new Date());
                    Calendar expireCalendar = Calendar.getInstance();
                    expireCalendar.setTime(memberPackageInfo.getExpireDate());

                    if (currentCalendar.after(expireCalendar)) {
                        memberPackageInfo
                            .setStatus((byte) PurchaseConstants.PACKAGE_STATUS_EXPIRED);
                        memberPackageDao.update(memberPackageInfo);
                        /*
                         * //Temp close the sms notification of package has
                         * expired
                         * //sendExpiredSMS(memberPackageInfo,SmsTemplateNoConstants
                         * .PACKAGE_EXPIRED_TEMPLATE_NO)
                         */
                    } else {
                        List<CodeInfo> packageToBeExpiredDays = codeMappingService
                            .getCodeInfoByType(CodeMappingType.PACKAGE_TO_BE_EXPIRED_DAYS
                                .getValue());
                        if (packageToBeExpiredDays != null && !packageToBeExpiredDays.isEmpty()) {
                            for (CodeInfo packageToBeExpiredDay : packageToBeExpiredDays) {
                                int daysBeforeExpired = this.getDays(
                                    memberPackageInfo.getExpireDate(), new Date());
                                if (daysBeforeExpired == Integer.valueOf(packageToBeExpiredDay
                                    .getValue())) {
                                    sendExpiredSMS(memberPackageInfo,
                                        SmsTemplateNoConstants.PACKAGE_TO_BE_EXPIRED_TEMPLATE_NO);
                                }
                            }
                        }
                    }

                }
            }
        } catch (Exception e) {
            throw new AppException("Exception processExpiredMemberPackage", e);
        }
    }

    private int getDays(Date startDate, Date endDate) {
        Date tempDate = endDate;
        if (tempDate == null) {
            tempDate = new Date();
        }
        Long start = startDate.getTime();
        Long end = tempDate.getTime();
        Long quot = start - end;
        return (int) (quot / (1000 * 60 * 60 * 24));
    }

    private void sendExpiredSMS(MemberPackageInfo memberPackageInfo, String templateNo)
        throws AppException {
        try {
            MemberInfo memberInfo = memberDao.findById(memberPackageInfo.getActiveMemberId());
            CarPlateInfo carPlateInfo = carPlateDao.findById(memberPackageInfo.getActiveCarId());
            User user = userDao.getUserByDealerId(memberPackageInfo.getActiveDealerId());
            if (memberInfo != null && carPlateInfo != null && user != null) {
                // Send SMS
                Map<String, String> paraMap = new HashMap<String, String>();
                paraMap.put(SmsTemplateVariable.VARIABLE_MEMBER_NAME, memberInfo.getMemberName());
                paraMap.put(SmsTemplateVariable.VARIABLE_CAR_PLATE_NUMBER,
                    carPlateInfo.getCarPlate());
                paraMap.put(SmsTemplateVariable.VARIABLE_PACKAGE_NAME, memberPackageInfo
                    .getPackageDefinition().getName());
                paraMap.put(SmsTemplateVariable.VARIABLE_PACKAGE_NUM,
                    memberPackageInfo.getPackageNumber());
                paraMap.put(SmsTemplateVariable.VARIABLE_DEALER_NAME, user.getName());

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                paraMap.put(SmsTemplateVariable.VARIABLE_EXPIRE_DATE,
                    sdf.format(memberPackageInfo.getExpireDate()));
                paraMap.put(SmsTemplateVariable.VARIABLE_PURCHASE_DATE,
                    sdf.format(memberPackageInfo.getPurchaseDate()));
                SmsContentDetailDto smsDto = new SmsContentDetailDto();
                smsDto.setParaMap(paraMap);
                if (Utils.notEmpty(memberInfo.getMobilePhone())) {
                    smsDto.setDestMobile(Long.valueOf(memberInfo.getMobilePhone()));
                    smsDto.setTemplateNo(templateNo);
                    smContentService.createSmsContent(smsDto);

                }
            }
        } catch (Exception e) {
            throw new AppException("Exception sendExpiredSMS", e);
        }
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2015年9月5日
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#getMemberPackageInfoByActiveDealerIdAndActiveMemberId(java.lang.Long,
     *      java.lang.Long)
     **/
    @Override
    public List<MemberPackageInfo> getMemberPackageInfoByActiveDealerIdAndActiveMemberId(
        Long dealerId, Long memberId) throws AppException {
        return memberPackageDao.getMemberPackageInfoByActiveDealerIdAndActiveMemberId(dealerId,
            memberId);
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : 2015年9月6日
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#updateMemberPackageInfoByMemberPackageInfo(com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo)
     **/
    @Override
    public void updateMemberPackageInfoByMemberPackageInfo(MemberPackageInfo memberPackageInfo,
        Long newMemberId) throws AppException {
        memberPackageDao.updateMemberPackageInfoByMemberPackageInfo(memberPackageInfo, newMemberId);
    }

    @Override
    public void processNotificationBeforeActivication() throws AppException {

        try {
            List<MemberPackageInfo> memberPackageInfoList = memberPackageDao
                .getMemberPackageList(PurchaseConstants.PACKAGE_STATUS_SALED);
            for (MemberPackageInfo memberPackageInfo : memberPackageInfoList) {
                if (memberPackageInfo != null) {
                    Calendar currentCalendar = Calendar.getInstance();
                    currentCalendar.setTime(new Date());
                    Calendar purchaseCalendar = Calendar.getInstance();
                    purchaseCalendar.setTime(memberPackageInfo.getPurchaseDate());
                    // add one month
                    purchaseCalendar.add(Calendar.MONTH, 1);

                    if (currentCalendar.after(purchaseCalendar)) {
                        memberPackageInfo
                            .setStatus((byte) PurchaseConstants.PACKAGE_STATUS_EXPIRED);
                        memberPackageDao.update(memberPackageInfo);
                        sendExpiredSMS(memberPackageInfo,
                            SmsTemplateNoConstants.PACKAGE_EXPIRED_TEMPLATE_NO);
                    }

                }
            }
        } catch (Exception e) {
            throw new AppException("Exception processExpiredMemberPackage", e);
        }

    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Oct 16, 2015
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#getMaxMemberPackageInfoByCardPrefix(java.lang.String)
     **/
    @Override
    public MemberPackageInfo getMaxMemberPackageInfoByNonPhysicalCardPrefix(String perfix) throws AppException {
        return memberPackageDao.getMaxMemberPackageInfoByNonPhysicalCardPrefix(perfix);
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Oct 21, 2015
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#cancelOrder(com.cap.bts.crmdp.dealer.purchase.domain.MemberPackageInfo)
     **/
    @Override
    public WSCrmCancelOrderResultDto cancelOrder(WSCrmOrderDto dto) {
        WSCrmCancelOrderResultDto resultDto = new WSCrmCancelOrderResultDto();
        
        MemberPackageInfo mpi = new MemberPackageInfo();
        try {
            if (dto.getCardNumberList() != null) {
                for (String cardNumber : dto.getCardNumberList()) {
                    mpi.setPackageNumber(cardNumber);
                    MemberPackageInfo memberPackageInfo = memberPackageDao
                        .getCancelMemberPackageInfoMars(mpi);
                    
                    MemberPackageInfo updateDto = null;
                    
                    if (memberPackageInfo != null) {
                        updateDto = memberPackageDao.findById(memberPackageInfo.getId());
                        
                        //@annson 2016-01-14 取消订单时删除tm_member_package_redemption的记录
                        packageRedemptionDao.deleteByPackageId(memberPackageInfo.getId());
                    }
                    if (updateDto != null) {
                        PackageDefinition packageDefinition=packageDefinitionDao.getPackageDefinitionInfoById(updateDto.getPackageDefinition().getId());
                        //增加库存
                        if(packageDefinition!=null){
                            CardInventory ci=cardInventoryDao.getCardInventoryInfo(packageDefinition.getCardDefinition().getId(), updateDto.getDealerId());
                            ci.setOnhandQuantity(ci.getOnhandQuantity()+1);
                        }
                        
                        if (updateDto.getCardDefinition().getIsPhysicalCard().intValue() == 1) {
                            updateDto.setCarId(null);
                            updateDto.setDealerId(null);
                            updateDto.setMemberId(null);
                            updateDto.setPurchaseDate(null);
                            updateDto.setActualPrice(null);
                            updateDto.setPackageNumber(cardNumber);
                            updateDto.setStatus((byte) 0);
                            updateDto.setPackageDefinition(null);
                            updateDto.setMarsLockStatus(0);
                            updateDto.setSoNumberCancel(dto.getSoNumber());
                            
                            updateDto.setActiveCarId(null);
                            updateDto.setActiveDate(null);
                            updateDto.setActiveMemberId(null);
                            updateDto.setActiveDealerId(null);
                            updateDto.setExpireDate(null);
                            
                            memberPackageDao.update(updateDto);
                        } else {
                            memberPackageDao.remove(updateDto.getId());
                        }
                    }
                }
            }else{
                resultDto.setStatusCode(MARSConstants.RESULT_STATUS_CODE_FAIL);
                resultDto.setResultMessage("cardNumberList is null");
                return resultDto;
            }
        } catch (Exception e) {
            resultDto.setStatusCode(MARSConstants.RESULT_STATUS_CODE_FAIL);
            resultDto.setResultMessage(e.getLocalizedMessage());
            LOGGER.error("cancelOrder", e);
            return resultDto;
        }
        resultDto.setStatusCode(MARSConstants.RESULT_STATUS_CODE_SUCCESS);
        resultDto.setResultMessage("success");
        return resultDto;
    }

    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Oct 23, 2015
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#settlement(com.cap.bts.crmdp.webservice.dto.WSCrmOrderDto)
     **/
    @Override
    public WSCrmSettlementResultDto settlement(WSCrmSettlementDto dto) {
        WSCrmSettlementResultDto resultDto = new WSCrmSettlementResultDto();
        MemberPackageInfo updateDto = null;
        MemberPackageInfo mpi = new MemberPackageInfo();
        try {
            if (dto.getCardNumberList() != null) {
                for (String cardNumber : dto.getCardNumberList()) {
                    mpi.setPackageNumber(cardNumber);
                    MemberPackageInfo memberPackageInfo = memberPackageDao
                        .getCancelMemberPackageInfoMars(mpi);
                    if (memberPackageInfo != null) {
                        updateDto = memberPackageDao.findById(memberPackageInfo.getId());
                    }
                    if (updateDto != null) {
                        if (updateDto.getCardDefinition().getIsPhysicalCard() == 1) {
                            resultDto.setActivation("1");
                        } else {
                            resultDto.setActivation("0");
                        }
                        resultDto.setStatusCode("1");
                        resultDto.setResultMessage("success");
                        
                        updateDto.setMarsLockStatus(0);
                        updateDto.setSoNumberSettle(dto.getSoNumber());
                        
                        memberPackageDao.update(updateDto);
                        
                        //@annson 虚拟卡发送短信，由购买激活时转到结算时发送
                        if ((memberPackageInfo.getPackageDefinition().getIsPhysicalCard().equals(PurchaseConstants.NON_FHYSICAL_CARD)) 
                        		) {
                            // send SMS Message
                            Map<String, String> paraMap = new HashMap<String, String>();
                            MemberInfo memberInfo = memberDao.findById(memberPackageInfo.getMemberId());
                            SmsContentDetailDto smsDto = new SmsContentDetailDto();
                            if (memberInfo != null) {
                                paraMap.put(SmsTemplateVariable.VARIABLE_MEMBER_NAME,
                                    memberInfo.getMemberName());
                                paraMap.put(SmsTemplateVariable.VARIABLE_PACKAGE_NAME, memberPackageInfo
                                    .getPackageDefinition().getName());
                                paraMap.put(SmsTemplateVariable.VARIABLE_PACKAGE_NUM,
                                    memberPackageInfo.getPackageNumber());
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                paraMap.put(SmsTemplateVariable.VARIABLE_EXPIRE_DATE,
                                    sdf.format(memberPackageInfo.getExpireDate()));
                                
                                smsDto.setParaMap(paraMap);
                                smsDto.setDestMobile(Long.valueOf(memberInfo.getMobilePhone()));
                                smsDto
                                    .setTemplateNo(SmsTemplateNoConstants.PACKAGE_ACTIVE_NOTIFICATION_TEMPLATE_NO);
                                smContentService.createSmsContent(smsDto);
                            }
                        }
                    }
                }
            }else{
                resultDto.setStatusCode(MARSConstants.RESULT_STATUS_CODE_FAIL);
                resultDto.setResultMessage("cardNumberList is null");
                return resultDto;
            }
        } catch (Exception e) {
            resultDto.setStatusCode("0");
            resultDto.setResultMessage(e.getLocalizedMessage());
            LOGGER.error("settlement", e);
            return resultDto;
        }
        return resultDto;
    }
    
    
    /**
     * {@inheritDoc} overridden:
     * 
     * @Date : Oct 29, 2015
     * @see com.cap.bts.crmdp.dealer.purchase.service.IMemberPackageService#getPackageListForReportByMember(java.lang.Long, java.lang.Long)
     **/
    @Override
    public List<MemberPackagesReportDto> getPackageListForReportByMember(Long memberId, Long carId) throws AppException {
    	List<MemberPackagesReportDto> dataList = new ArrayList<MemberPackagesReportDto>();
    	
    	Map<Long, MemberPackagesReportDto> plateMap = new HashMap<Long, MemberPackagesReportDto>();
    	
    	MemberPackagesReportDto nonePlate = new MemberPackagesReportDto();
    	if(carId == null){
    		//不显示未激活卡
    		dataList.add(nonePlate);
    	}
    	
    	//获取套餐信息
    	List<Object[]> list = memberPackageDao.getPackageListForReportByMember(memberId, carId);
    	
    	List<ShowMemberPackageInfoReportDto> packageList = new ArrayList<ShowMemberPackageInfoReportDto>(); 
    	
    	List<Long> packageIdList = new ArrayList<Long>();
    	Map<Long, ShowMemberPackageInfoReportDto> map = new HashMap<Long, ShowMemberPackageInfoReportDto>();
    	
    	for(Object[] obj : list){
    		ShowMemberPackageInfoReportDto packageDto = new ShowMemberPackageInfoReportDto();
    		
    		packageDto.setPrice((Double) obj[0]);
    		packageDto.setName((String)obj[1]);
    		packageDto.setPackageNumber((String)obj[2]);
    		packageDto.setStatus((Byte)obj[3]);
    		packageDto.setPurchaseDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[4]));
    		packageDto.setActiveDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[5]));
    		packageDto.setExpireDate(Utils.formatDate(CommonConstants.DATE_FORMAT_YYMMDD,(Date)obj[6]));
    		BigInteger id = (BigInteger) obj[7];
    		packageDto.setId(id.longValue());
    		BigInteger tmpCarId = (BigInteger)obj[8];
    		if(tmpCarId != null){
    			packageDto.setCarId(tmpCarId.longValue());
    		}
    		packageDto.setCarPlate((String)obj[9]);
    		if(packageDto.getStatus() == 3){
    			packageDto.setHasUnActived(true);
    		}else{
    			packageDto.setHasUnActived(false);
    		}
    		
    		
    		map.put(packageDto.getId(), packageDto);
    		packageIdList.add(packageDto.getId());
    		packageList.add(packageDto);
    		
    		
    		if(null == packageDto.getCarId()){
    			nonePlate.getShowMemberPackageInfoReportList().add(packageDto);
    		}else{
    			MemberPackagesReportDto tmpPlate = plateMap.get(packageDto.getCarId());
    			if(tmpPlate == null){
    				tmpPlate = new MemberPackagesReportDto();
    				tmpPlate.setCarPlate(packageDto.getCarPlate());
    				dataList.add(tmpPlate);
    				plateMap.put(packageDto.getCarId(), tmpPlate);
    			}
    			
    			tmpPlate.getShowMemberPackageInfoReportList().add(packageDto);
    		}
    		
    		
    		if(packageDto.getStatus() > 1){
    			//套餐使用明细
    			List<Object[]> packageRedemList = packageRedemptionDao.getPackageRedemListByPackageId(packageDto.getId());
    			if(packageRedemList != null && !packageRedemList.isEmpty()){
    				packageDto.setPackageRedemList(packageRedemList);
    			}
    		}
    		
    	}
    	
    	
    	if(!packageIdList.isEmpty()){
    		//获取所有套餐明细信息
    		List<Object[]> detailList = packageRedemptionDao.getPackageListReportDetailByPackageIds(packageIdList);
    		
    		//将套餐明细归置套餐下
    		for (Object[] objects : detailList) {
    			
    			ShowMemberPackageInfoReportDto dto = map.get(((BigInteger)objects[0]).longValue());
    			if(dto != null){
    				dto.getMemberPackageList().add(objects);
    			}
    		}
    	}
    	
    	if(nonePlate.getShowMemberPackageInfoReportList().isEmpty()){
    		dataList.remove(nonePlate);
    	}
    	
    	
    	return dataList;
    	
    	
    }

	@Override
	public List<MemberAndDealerInfoDto> getMemberAndDealerInfoDtoByMARSIdAndDearId(Long dealerId, String marsMemberId)
			throws AppException {
		return memberPackageDao.getMemberAndDealerInfoDtoByMARSIdAndDearId(dealerId, marsMemberId);
	}

	@Override
	public Long getUsedRedemptionCountByPackageNumber(String packageNumber) throws AppException {
		
		return packageRedemptionDao.getUsedRedemptionCountByPackageNumber(packageNumber);
	}
	
	
	@Override
	public void deleteOrderGift(Long activeMemberId) throws AppException {
		//获取会员套餐状态
		List<Object[]> statusList = memberPackageDao.getPackageStatusByMemberId(activeMemberId);
		
		if(!statusList.isEmpty()){
			Object[] obj = statusList.get(0);
			BigDecimal noGift = (BigDecimal)obj[0];
			BigDecimal gift = (BigDecimal)obj[1];
			
			//没有其它卡或其它卡为0，但礼品卡不为0，执行退礼品卡操作
			if((noGift == null || noGift.intValue() == 0) && gift != null && gift.intValue() > 0){
				memberPackageDao.deleteGiftByMemberId(activeMemberId);
			}
		}
		
		
	}

}
